<template>
  <div>
    <!-- 搜索框 -->
    <div class="search">
      <el-form :inline="true" class="demo-form-inline" ref="form" :model="form">
        <el-form-item>
          <el-input v-model="form.nickname" placeholder="请输入用户昵称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="form.consignee" placeholder="请输入收货人名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="form.orderSn" placeholder="请输入订单编号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <div class="block">
            <el-date-picker v-model="form.start" type="daterange" align="right" unlink-panels range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item>
          <el-select v-model="form.orderStatusArray" placeholder="请选择订单状态">
            <el-option label="用户取消" :value="102"></el-option>
            <el-option label="系统取消" :value="103"></el-option>
            <el-option label="已付款" :value="201"></el-option>
            <el-option label="申请退款" :value="202"></el-option>
            <el-option label="已退款" :value="203"></el-option>
            <el-option label="已发货" :value="301"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">查找</el-button>
          <el-button type="primary" @click="handchu" icon="el-icon-download">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%" border v-loading="loading">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand" style="display: flex; gap: 10px;"
            v-for="item in props.row.goodsVoList" :key="item.id">
            <el-form-item>
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-image style="width: 40px; height: 40px" :src="item.picUrl"></el-image>
                <span>{{ item.goodsName }}</span>
              </div>
            </el-form-item>
            <el-form-item label="规格：">
              <span>{{ item.specifications }}</span>
            </el-form-item>
            <el-form-item label="单价：">
              <span>{{ item.price }} 元</span>
            </el-form-item>
            <el-form-item label="数量：">
              <span>{{ item.number }} 件</span>
            </el-form-item>
            <el-form-item label="小计：">
              <span>{{ item.price * item.number }} 元</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" prop="orderSn" min-width="130" align="center">
      </el-table-column>
      <el-table-column label="用户头像" prop="id" min-width="90" align="center">
        <div class="cell"><span class="el-avatar el-avatar--circle"></span></div>
      </el-table-column>
      <el-table-column label="下单用户" prop="userName" min-width="100" align="center">
      </el-table-column>
      <el-table-column label="下单时间" prop="addTime" min-width="110" align="center"
        :show-overflow-tooltip="shouldShowTooltip">
      </el-table-column>
      <el-table-column label="订单状态" prop="id" width="100" align="center">
        <template slot-scope="scope">
          <el-tag class="tagOne" v-if="scope.row.orderStatus === 103" type="success">系统取消</el-tag>
          <el-tag class="tagOne" v-if="scope.row.orderStatus === 202" type="warning">申请退款</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" prop="orderPrice" min-width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.orderPrice }} 元</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" prop="actualPrice" min-width="90" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.actualPrice }} 元</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" prop="" min-width="100" align="center">
      </el-table-column>
      <el-table-column label="收货人" prop="consignee" min-width="100" align="center">
        <template slot-scope="scope">
          <span class="spn">{{ scope.row.consignee }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货电话" prop="mobile" min-width="110" align="center">
      </el-table-column>
      <el-table-column label="物流单号" prop="" min-width="100" align="center">
      </el-table-column>
      <el-table-column label="物流渠道" prop="" min-width="100" align="center">
      </el-table-column>
      <el-table-column label="操作" prop="id" min-width="360" align="center">
        <template slot-scope="scope">
          <div class="cell">
            <el-button type="button" @click="handleDetail(scope.row)"
              class="el-button el-button--primary el-button--mini"><span>详情</span></el-button>
            <el-button type="button" @click="handleDel(scope.row)"
              class="el-button el-button--danger el-button--mini"><span>删除</span></el-button>
            <el-button type="button" @click="handlePay(scope.row)"
              class="el-button el-button--warning el-button--mini"><span>收款</span></el-button>
            <el-button type="button" @click="handleShip(scope.row)"
              class="el-button el-button--primary el-button--mini"><span>发货</span></el-button>
            <el-button type="button" @click="handleRefund(scope.row)"
              class="el-button el-button--danger el-button--mini"><span>退款</span></el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40]" :page-size="20" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 详情 -->
    <el-dialog title="订单详情" :visible.sync="dialogVisible" width="50%" :data="VisibleData">
      <div class="conter">
        <el-form :model="ListQuery" ref="ListQuery" label-width="100px" class="demo-ListQuery" :data="ListQuery">
          <el-form-item label="订单编号" prop="orderSn">
            <span>{{ ListQuery.orderSn }}</span>
          </el-form-item>
          <el-form-item label="订单状态" prop="keywords">
            <div class="cell"><span class="el-tag el-tag--mini el-tag--light">已发货</span></div>
          </el-form-item>
          <el-form-item label="订单用户" prop="userName">
            <span>{{ ListQuery.userName }}</span>
          </el-form-item>
          <el-form-item label="用户留言" prop="mobile">
            <span></span>
          </el-form-item>
          <el-form-item label="收货信息" prop="consignee">
            <span>(收货人){{ ListQuery.consignee }}(手机号){{ ListQuery.mobile }}(地址)
              {{ ListQuery.address }}</span>
          </el-form-item>
          <!-- 商品信息 -->
          <el-form-item label="商品信息">
            <el-table :data="ProductInformation" border style="width: 100%">
              <el-table-column prop="goodsName" label="商品名称" min-width="140" align="center">
              </el-table-column>
              <el-table-column prop="goodsId" label="商品编号" min-width="120" align="center">
              </el-table-column>
              <el-table-column prop="specifications" label="货品规格" min-width="120" align="center">
              </el-table-column>
              <el-table-column prop="price" label="货品价格" min-width="120" align="center">
              </el-table-column>
              <el-table-column prop="number" label="货品数量" min-width="80" align="center">
              </el-table-column>
              <el-table-column prop="picUrl" label="货品图片" min-width="120" align="center">
                <template slot-scope="scope">
                  <img :src="scope.row.picUrl" style="width: 40px;height: 40px;"></img>
                </template>
              </el-table-column>
            </el-table>

          </el-form-item>
          <el-form-item label="费用信息" prop="desc">
            <span>(实际费用){{ ListQuery.actualPrice }}元 = (商品总价){{ ListQuery.orderPrice }}元 + (快递费用)0元 - (优惠减免)0元 -
              (积分减免)0元</span>
          </el-form-item>
          <el-form-item label="支付信息" prop="desc">
            <span>（支付渠道）微信支付（支付时间）</span>
          </el-form-item>
          <el-form-item label="快递信息" prop="desc">
            <span>（快递公司）{{ ListQuery.shipChannel }}（快递单号）{{ ListQuery.shipSn }}（发货时间）</span>
          </el-form-item>
          <el-form-item label="退款信息" prop="desc">
            <span>（退款金额）元（退款类型）（退款备注）（退款时间）</span>
          </el-form-item>
          <el-form-item label="收货信息" prop="desc">
            <span>（确认收货时间）</span>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="printModal">打 印</el-button>
      </span>
    </el-dialog>
    <!-- 收款 -->
    <div>
      <el-dialog title="订单收款" :visible.sync="OrderCollections" width="40%">
        <div class="content">
          <el-form label-width="100px" class="demo-ListQuery" :data="OrderCollection">
            <el-form-item prop="orderSn">
              <div style="margin-bottom: 10px;margin-left: 32px"> 确认当前订单（订单编号 {{ OrderCollection.orderSn }} ） 已经完成线下收款 ？
              </div>
            </el-form-item>
            <el-form-item label="订单金额" prop="orderPrice">
              <el-input disabled style="width: 140px;" placeholder="0.01"></el-input>
            </el-form-item>
            <el-form-item label="付款金额" prop="actualPrice">
              <el-input v-model="OrderCollection.actualPrice" style="width: 140px;"
                @focus="handleInputFocus"></el-input>
            </el-form-item>
            <el-form-item>
              <el-table :data="receiveMoney" style="width: 100%">
                <el-table-column prop="goodsName" label="商品" align="center" min-width="200px">
                </el-table-column>
                <el-table-column prop="specifications" label="规格" align="center">
                </el-table-column>
                <el-table-column prop="number" label="下单数量" align="center">
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button @click="handelOrder">取 消</el-button>
          <el-button v-if="isTrue" type="primary" @click="submitForms()">确 定</el-button>
          <el-button v-if="!isTrue" type="primary" @click="handelFrom()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 计算金额差值 -->
      <el-dialog class="spwd" width="30%" :visible.sync="Difference" style="z-index: 9999999999;">
        <h4>差额 {{ differenceValue }}元， 是否确认提交?</h4>
        <div slot="footer">
          <el-button @click="Difference = false">取 消</el-button>
          <el-button type="primary" @click="submitForms()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 发货 -->
    <el-dialog title="发货" :visible.sync="dialogVisibles1" width="50%">
      <div class="content">
        <el-form :model="Delivery" ref="Delivery" label-width="100px" class="demo-ListQuery" :data="Delivery">
          <el-form-item prop="orderSn">
            <span></span>
          </el-form-item>
          <el-form-item label="活动区域">
            <el-select v-model="formInline.region" placeholder="请选择快递">
              <el-option label="中通快递 " value="ZTO"></el-option>
              <el-option label="圆通速递" value="YTO"></el-option>
              <el-option label="韵达速递" value="YD"></el-option>
              <el-option label="邮政快递包裹" value="YZPY"></el-option>
              <el-option label="EMS" value="EMS"></el-option>
              <el-option label="德邦快递" value="DBL"></el-option>
              <el-option label="快捷快递" value="FAST"></el-option>
              <el-option label="宅急送" value="ZJS"></el-option>
              <el-option label="TNT快递" value="TNT"></el-option>
              <el-option label="UPS" value="UPS"></el-option>
              <el-option label="DHL" value="DHL"></el-option>
              <el-option label="FEDEX联邦(国内件)" value="FEDEX"></el-option>
              <el-option label="FEDEX联邦(国际件)" value="FEDEX_GJ"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="快递编号" prop="actualPricess" style="display: flex;">
            <el-input style="width: 300px;" v-model="actualPricess"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibles1 = false">取 消</el-button>
        <el-button type="primary" @click="submitForms1()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 退款 -->
    <el-dialog title="发货" :visible.sync="dialogVisibles2" width="50%">
      <div class="content">
        <el-form label-width="100px" class="demo-ListQuery">
          <el-form-item prop="orderSn">
          </el-form-item>
          <el-form-item label="退款金额" prop="refundReason" style="display: flex;">
            <el-input disabled="" style="width: 500px;" v-model="refundReason"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibles2 = false">取 消</el-button>
        <el-button type="primary" @click="Refund">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import { listOrder, deleteOrder, payOrder, shipOrder, refundOrder } from '@/api/order'
import dayjs from 'dayjs';
import * as XLSX from "xlsx";
export default {
  data() {
    return {
      refundReason: '',
      actualPricess: '',
      formInline: {
        user: '',
        region: '',
        id: '',
        username: '',
        mobile: ''
      },
      dialogVisibles1: false,
      refundReasons: '',
      dialogVisibles2: false,
      OrderCollections: false,
      isTrue: true,
      Difference: false,
      ProductInformation: [],
      Delivery: [],
      receiveMoney: [],
      OrderCollection: {
        orderSn: '',
        actualPrice: '',
        orderPrice: ''
      },
      dialogVisible: false,
      shouldShowTooltip: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      value1: '',
      handelObj: '',
      loading: false,
      tableData: [{
        id: '12987122',
        name: '好滋好味鸡蛋仔',
        category: '江浙小吃、小吃零食',
        desc: '荷兰优质淡奶，奶香浓而不腻',
        address: '上海市普陀区真北路',
        shop: '王小虎夫妻店',
        shopId: '10333'
      }, {
        id: '12987123',
        name: '好滋好味鸡蛋仔',
        category: '江浙小吃、小吃零食',
        desc: '荷兰优质淡奶，奶香浓而不腻',
        address: '上海市普陀区真北路',
        shop: '王小虎夫妻店',
        shopId: '10333'
      }, {
        id: '12987125',
        name: '好滋好味鸡蛋仔',
        category: '江浙小吃、小吃零食',
        desc: '荷兰优质淡奶，奶香浓而不腻',
        address: '上海市普陀区真北路',
        shop: '王小虎夫妻店',
        shopId: '10333'
      }, {
        id: '12987126',
        name: '好滋好味鸡蛋仔',
        category: '江浙小吃、小吃零食',
        desc: '荷兰优质淡奶，奶香浓而不腻',
        address: '上海市普陀区真北路',
        shop: '王小虎夫妻店',
        shopId: '10333'
      }],
      ListQuery: {
        name: '',
        desc: '',
        floorPrice: '',
        role: localStorage.getItem('role')
      },
      VisibleData: '',
      form: {
        nickname: '',
        consignee: '',
        orderSn: '',
        start: ''
      },
      differenceValue: '',
      total: 0,
      page: 1,
      limit: 20,
    }
  },
  methods: {
    // 打印功能实现
    printModal() {
      // 获取模态框元素
      const modal = document.querySelector('.el-dialog');
      // 创建一个临时的iframe
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      document.body.appendChild(iframe);
      const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      // 将模态框的内容复制到iframe中
      iframeDoc.open();
      iframeDoc.write('<html><head><style>' + document.styleSheets[0].cssText + '</style></head><body>');
      iframeDoc.write(modal.outerHTML);
      iframeDoc.write('</body></html>');
      iframeDoc.close();
      // 在iframe中触发打印
      iframe.contentWindow.focus();
      iframe.contentWindow.print();
      // 打印完成后移除iframe
      setTimeout(() => {
        document.body.removeChild(iframe);
      }, 1000);
    },
    // 退款
    handleRefund(row) {
      this.dialogVisibles2 = true;
      this.refundReason = JSON.parse(JSON.stringify(row)).actualPrice
      this.refundReasons = JSON.parse(JSON.stringify(row))
    },
    Refund() {
      refundOrder({
        orderId: this.refundReasons.id,
        refundMoney: this.refundReason,
      }).then(res => {
        if (res.code === 0) {
          this.dialogVisibles2 = false;
          this.$message({
            type: 'success',
            message: '退款成功'
          })
          this.handleGetList();
        } else {
          this.$message({
            type: 'error',
            message: '订单不能退款'
          })
        }
      })
    },
    submitForms1() {
      shipOrder({
        orderId: this.Delivery.id,
        shipChannel: this.formInline.region,
        shipSn: this.actualPricess
      }).then(res => {
        if (res.code === 0) {
          this.dialogVisibles1 = false;
          this.$message({
            type: 'success',
            message: '发货成功'
          })
          this.handleGetList();
        } else {
          this.$message({
            type: 'error',
            message: '订单不能确认收货'
          })
        }
      })
    },
    // 发货
    handleShip(row) {
      this.dialogVisibles1 = true;
      this.Delivery = JSON.parse(JSON.stringify(row))
    },
    // 取消
    handelOrder() {
      this.OrderCollections = false;
      this.isTrue = true;
    },
    handelFrom() {
      this.Difference = true;
    },
    // 收款
    submitForms() {
      this.Difference = false;
      payOrder({
        newMoney: this.OrderCollection.actualPrice,
        oldMoney: 0.01,
        orderId: this.OrderCollection.id,
        orderSn: this.OrderCollection.orderSn
      }
      ).then(res => {
        if (res.code === 0) {
          this.Difference = false;
          this.$message({
            type: 'success',
            message: '收款成功'
          })
          this.handleGetList();
        } else {
          this.$message({
            type: 'error',
            message: '当前订单状态不支持线下收款'
          })
        }
      })
    },
    handlePay(row) {
      // this.isTrue = false;
      this.OrderCollections = true;
      this.OrderCollection = JSON.parse(JSON.stringify(row))
      this.receiveMoney = JSON.parse(JSON.stringify(row.goodsVoList))
    },
    // 删除
    handleDel(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteOrder({ orderId: row.id }).then((res) => {
          if (res.errmsg === "订单不能删除") {
            this.$message({
              type: "warning",
              message: res.errmsg,
            });
          } else {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
          this.handleGetList();
        });
      });
    },
    // 详情
    handleDetail(row) {
      this.dialogVisible = true;
      this.ListQuery = JSON.parse(JSON.stringify(row))
      this.ProductInformation = JSON.parse(JSON.stringify(row.goodsVoList))
    },
    // 导出
    handchu() {
      // 点击导出的时候把现有数据生成一个新的数组 以中文作为key然后在导出
      let demo = [];
      for (let i = 0; i < this.tableData.length; i++) {
        let obje = {
          订单ID: this.tableData[i].id,
          订单编号: this.tableData[i].orderSn,
          用户ID: this.tableData[i].desc,
          订单状态: this.tableData[i].orderStatus,
          是否删除: this.tableData[i].code,
          收货人: this.tableData[i].consignee,
          收货联系电话: this.tableData[i].mobile,
          收货地址: this.tableData[i].address,
        };
        demo.push(obje);
      }
      console.log(demo);
      const worksheet = XLSX.utils.json_to_sheet(demo); //这里面传入要导出的表格数据
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "data"); //data为自定义表格名字
      XLSX.writeFile(workbook, "用户信息.xlsx"); //one.xlsx指的是文件名
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.limit = val
      this.handleGetList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.handleGetList();
    },
    // 查询
    handleSearch() {
      this.loading = true;
      listOrder({
        nickname: this.form.nickname,
        consignee: this.form.consignee,
        orderSn: this.form.orderSn,
        orderStatusArray: this.form.orderStatusArray,
        start: dayjs(this.form.start[0]).format('YYYY-MM-DD HH:mm:ss'),
        end: dayjs(this.form.start[1]).format('YYYY-MM-DD HH:mm:ss'),
        page: this.form.page,
        limit: this.form.limit
      }).then((res) => {
        this.tableData = res.data.list;
        this.loading = false;
      })
    },
    // 获取列表
    handleGetList() {
      this.loading = true;
      listOrder({
        page: this.page,
        limit: this.limit
      }).then((res) => {
        this.tableData = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    handleInputFocus() {
      this.isTrue = false;
    },
  },
  // 监听
  watch: {
    'OrderCollection.actualPrice': {
      handler(newVal) {
        if (newVal !== '') {
          this.differenceValue = Math.abs(parseFloat(newVal) - 0.01);
        }
      },
      OrderCollections(newVal) {
        if (!newVal) {
          this.isTrue = true;
        }
      },
      deep: true
    }
  },
  mounted() {
    // 用于日期回显 显示当前时间
    const now = dayjs();
    const start = now.subtract(1, 'day').startOf('day');
    const end = now.endOf('day');
    this.form.start = [start.toDate(), end.toDate()];
    this.handleGetList();
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}

.pagination {
  background: #fff;
  padding: 32px 16px;
  margin-top: 30px;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.tagOne {
  height: 20px;
  padding: 0 5px;
  line-height: 19px;
  background-color: #e8f4ff;
  border-color: #d1e9ff;
  display: inline-block;
  font-size: 12px;
  color: #1890ff;
  border-width: 1px;
  border-style: solid;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
}

.spn {
  color: red;
  font-weight: bold;
}

.spwd {
  margin-top: 10% !important;
}
</style>